<template>
  <div class="common-layout">
    <el-container>
      <!--aside-->
      <el-aside width="400px">
        <el-card class="box-card" style='margin-bottom: 10px;'>
          <div class="text item">
            <el-form :model="loginForm" :rules="loginRules" ref="loginForm" class="demo-form-inline" label-width="100px">
              <el-form-item label="服务器地址:" required prop="ip">
                <el-input v-model="loginForm.ip" placeholder="请输入IP地址"></el-input>
              </el-form-item>
              <el-form-item label="端口号:" required prop="port">
                <el-input v-model="loginForm.port" placeholder="" style="width: 60px"></el-input>
              </el-form-item>
<!--              <el-form-item label="分类:" required prop="type">-->
<!--                <el-radio-group v-model="loginForm.type">-->
<!--                  <el-radio label="1">控制台</el-radio>-->
<!--                  <el-radio label="2">抢购机</el-radio>-->
<!--                </el-radio-group>-->
<!--              </el-form-item>-->
              <el-form-item label="本机名称:" required prop="serverName">
                <el-input v-model="loginForm.serverName" placeholder=""></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="mini" class="btnMini" @click="handleLogin('loginForm')">登录</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        <!--预测数据-->
<!--        <el-card class="box-card">-->
<!--          <template #header>-->
<!--            <div class="card-header">-->
<!--              <span>预测数据</span>-->
<!--              &lt;!&ndash;操作按钮&ndash;&gt;-->
<!--              <el-button-group class="ml-4" style="float: right;">-->
<!--                <el-button type="primary" size='mini' class="btnMini" title="预测" @click="handleForecast">预测</el-button>-->
<!--                <el-button type="primary" size='mini' class="btnMini" title="刷新">刷新</el-button>-->
<!--              </el-button-group>-->
<!--            </div>-->
<!--          </template>-->
<!--          <div class="text item">-->
<!--            &lt;!&ndash;预测数据&ndash;&gt;-->
<!--            <el-table :data="forecastData" stripe style="width: 100%" @row-click="handleForecastRowClick">-->
<!--              <el-table-column prop="chipCode" label="产品型号" width="150" />-->
<!--              <el-table-column prop="operateDate" label="操作时间" width="100" />-->
<!--              <el-table-column prop="forecastDate" label="预测时间" width="100" />-->
<!--            </el-table>-->
<!--          </div>-->
<!--        </el-card>-->
      </el-aside>
      <el-container>
        <!--header-->
        <el-header style="height: 0px">

        </el-header>
        <!--main-->
        <el-main>
          <el-row>
            <el-col :span="24">
              <!--操作Tabs-->
              <el-card class="box-card">
                <div class="text item">
                  <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                    <el-tab-pane label="人工模式" name="first">
                      <!--transfer-->
                      <el-transfer
                        style="text-align: left; display: inline-block; margin-bottom: 10px;"
                        v-model="selectedData"
                        filterable
                        :left-default-checked="[2, 3]"
                        :right-default-checked="[1]"
                        :titles="['抢购机列表', '选中列表']"
                        :format="{
                          noChecked: '${total}',
                          hasChecked: '${checked}/${total}'
                        }"
                        :data="clientData">
<!--                        <el-button class="transfer-footer" slot="left-footer" size="small">操作</el-button>-->
<!--                        <el-button class="transfer-footer" slot="right-footer" size="small">操作</el-button>-->
                      </el-transfer>
                      <!--人工模式-->
                      <el-form :model="artificialForm" :rules="artificialRules" ref="artificialForm" label-width="100px" class="demo-ruleForm">
                        <el-form-item label="型号:" prop="chipCode">
                          <el-input v-model="artificialForm.chipCode" style='width: 200px;'></el-input>
                        </el-form-item>
                        <el-form-item label="数量:" prop="buyNum">
                          <el-input v-model="artificialForm.buyNum" style='width: 200px;'></el-input>
                        </el-form-item>
                        <el-form-item>
                          <el-button type="primary" size="mini" class="btnMini" @click="handleSend('artificialForm')">发送</el-button>
                          <el-button size="mini" class="btnMini" @click="resetForm('artificialForm')">重置</el-button>
                        </el-form-item>
                      </el-form>
                    </el-tab-pane>
                    <el-tab-pane label="自动模式" name="second">自动模式</el-tab-pane>
                  </el-tabs>
                </div>
              </el-card>
            </el-col>
          </el-row>

        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
let msg = {
  code: 0,
  data: '',
  message: ''
}

/** 请求连接 */
const CLIENT_CONNECTION_CODE = 1;
const SERVER_CONNECTION_CODE = 2;
/** 心跳 */
const CLIENT_HEATER_CODE = 3;
const SERVER_HEATER_CODE = 4;
/** 发送数据 */
const CLIENT_SEND_CODE = 5;
const SERVER_SEND_CODE = 6;
/** 根据groupId加载数据 */
const CLIENT_LOAD_DATA_CODE = 7;
const SERVER_LOAD_DATA_CODE = 8;

import {getAkmUrl, getCookie} from '../utils/goods';
import tidata from '../tidata';
// import getUserIP from '../utils/common';
export default {
  name: 'TmConsole',
  components: {},
  data() {
    return {
      activeName: 'first',
      artificialForm: {
        chipCode: '',
        clientList: '',
        buyNum: 0
      },
      artificialRules: {
        chipCode: [
          { required: true, message: '请输入芯片型号', trigger: 'blur' }
        ],
        clientList: [
          { required: true, message: '请选择客户机', trigger: 'blur' }
        ],
        buyNum: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ]
      },
      loginForm: {
          ip: '',
          port: '8000',   
          serverName: '',
          type: '1'
      },
      loginRules: {
        ip: [
          { required: true, message: '请输入ip地址', trigger: 'blur' }
        ],
        port: [
          { required: true, message: '请输入端口号', trigger: 'blur' }
        ],
        serverName: [
            { required: true, message: '请输入客户机名称', trigger: 'blur' }
        ],
        type: [
            { required: true, message: '请选择分类', trigger: 'blur' }
        ]
      },
      forecastData: [
        // {
        //   operateDate: '11:30:00',
        //   chipCode: 'PCM1862DBTR',
        //   forecastDate: '11:45:00',
        // },
        // {
        //   operateDate: '11:30:00',
        //   chipCode: 'TPS2421-2DDAR',
        //   forecastDate: '11:45:00',
        // },
        // {
        //   operateDate: '11:30:00',
        //   chipCode: 'BQ24095DGQR',
        //   forecastDate: '11:45:00',
        // },
        // {
        //   operateDate: '11:30:00',
        //   chipCode: 'DP83826IRHBT',
        //   forecastDate: '11:45:00',
        // },
      ],
      selectedData: [],
      clientData: [],
      // websocket参数
      ipAddress: '',
      websock: null, //建立的连接
      lockReconnect: false, //是否真正建立连接
      timeout: 20 * 1000, //20秒一次心跳
      timeoutObj: null, //心跳心跳倒计时
      serverTimeoutObj: null, //心跳倒计时
      timeoutNum: null, //断开 重连倒计时
      //
    }
  },
  methods: {
    handleForecastRowClick(row, column, event) {
      this.artificialForm.chipCode = row.chipCode;
    },
    // 登录
    handleLogin(formName) {
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.initWebSocket(that.loginForm.ip, that.loginForm.port, that.loginForm.serverName);
        } else {
          return false;
        }
      });
    },
    // 预测
    handleForecast() {
      let that = this;
      // 跨域从后台拿到待预测的数据集
      // const url = 'http://localhost:8000/api/admin/chip/list';
      // let param = {
      //   groupId: 1
      // };
      // let configs = {
      //   headers: {
      //     'Content-type': 'application/x-www-form-urlencoded',
      //   },
      //   data: '',
      // }
      // this.$http.get(url, param, configs).then(function(response){
      //     debugger;
      // });
      // 拼装请求
      // let data = [
      //   "2N7001TDCKR",
      //   "6PAIC3104IRHBTQ1",
      //   "2N7001TDCKT",
      //   "6PAIC3104IRHBRQ1",
      //   "6PAIC3109TRHBQ1"
      // ];
      // let arrs = data.split(',');
      
      let arrs = tidata;
      let length = arrs.length;
      let opns = '';
      let opn = '';
      for (let i = 0; i < length; i++) {
        opn +=
          '{"orderable_material":"' +
          arrs[i].trim() +
          '","quantity_requested":1,"spq":3000,"custom_reel_enabled":true},'; // 2021-12-26 增加 价格。
      }
      opn = opn + '@@@';
      opn = opn.replace(',@@@', '');
      opns = '[' + opn + ']';
      let timeout = 6 * 1000;
      let url = '/product-folders/customreel/inventoryforecast';
      $.ajax({
					type: 'POST',
					url: url,
					timeout: timeout,
					data: opns,
					dataType: 'json',
					contentType: 'application/json',
					Accept: '*/*',
					cache: false,
					//async:false,
      }).done(function (result) {
        if(result){
          let curDate = new Date();
          let newDate = new Date();
          // 增加15分钟
          let min = newDate.getMinutes();
          newDate.setMinutes(min + 15);
          $.each(result, function (index, item) {
							console.log(item);
              // if(item.fulfilement) {
                let arr = {
                  operateDate: curDate.getHours()+':'+curDate.getMinutes()+':'+curDate.getSeconds(),
                  chipCode: item.orderable_material,
                  forecastDate: newDate.getHours()+':'+newDate.getMinutes()+':'+newDate.getSeconds(),
                }
                that.forecastData.push(arr);
              // }
					});
        }
      }).fail(function (a) {

      });

    },
    handleSend(formName) {
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = {
            chipCode: that.artificialForm.chipCode,
            servers: JSON.stringify(that.selectedData),
            buyNum: that.artificialForm.buyNum
          }
          that.msg = {
            code: CLIENT_SEND_CODE,
            data: data,
            message: ''
          }
          that.websocketsend(JSON.stringify(that.msg));
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    /*******************************************/
    // websocket方法
    initWebSocket(ip, port, serverName) {
      //建立连接
      //初始化weosocket
      // let timestamp = new Date().getTime();
      // const wsuri = "ws://"+ip+":"+port+"/websocket"+"/chip/"+serverName;
      const wsuri = "wss://"+ip+"/websocket"+"/chip/"+serverName;
      try {
        //建立连接
        this.websock = new WebSocket(wsuri);
        //连接成功
        this.websock.onopen = this.websocketonopen;
        //连接错误
        this.websock.onerror = this.websocketonerror;
        //接收信息
        this.websock.onmessage = this.websocketonmessage;
        //连接关闭
        this.websock.onclose = this.websocketclose;
      } catch (e) {
        // this.$message.error('未连接到服务器！');
      }
    },
    reconnect() {
      //重新连接
      var that = this;
      if (that.lockReconnect) {
        return;
      }
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      that.timeoutNum && clearTimeout(that.timeoutNum);
      that.timeoutNum = setTimeout(function() {
        //新连接
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    },
    reset() {
      //重置心跳
      var that = this;
      //清除时间
      clearTimeout(that.timeoutObj);
      clearTimeout(that.serverTimeoutObj);
      //重启心跳
      that.start();
    },
    start() {
      //开启心跳
      let self = this;
      self.timeoutObj && clearTimeout(self.timeoutObj);
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
      self.timeoutObj = setTimeout(function() {
        //这里发送一个心跳，后端收到后，返回一个心跳消息
        if (self.websock.readyState == 1) {
          //如果连接正常
          msg = {
            code: CLIENT_HEATER_CODE,
            data: 'heat',
            message: ''
          }
          self.websocketsend(JSON.stringify(msg));
          // self.websock.send("100");// 连接请求码100
        } else {
          //否则重连
          self.reconnect();
        }
        self.serverTimeoutObj = setTimeout(function() {
          //超时关闭
          self.websock.close();
        }, self.timeout);
      }, self.timeout);
    },
    websocketonopen() {
      //连接成功事件
      msg = {
        code: CLIENT_CONNECTION_CODE,
        data: 'connect',
        message: ''
      }
      this.websocketsend(JSON.stringify(msg));
      //提示成功
      // this.$message.success('连接成功！');
      // console.log("连接成功", 3);
      //开启心跳
      this.start();
    },
    websocketonerror(e) {
      //连接失败事件
      //错误
      // console.log("WebSocket连接发生错误");
      this.$message.error('未连接到服务器！');
      this.websock = null;
      //重连
      // this.reconnect();
    },
    websocketclose(e) {
      //连接关闭事件
      //提示关闭
      // console.log("连接已关闭");
      // this.$message.warning('连接已断开！');
      //重连
      // this.reconnect();
    },
    websocketonmessage(event) {
      let that = this;
      //接收服务器推送的信息
      // console.log("收到服务器信息",event.data);
      let result = JSON.parse(event.data);
      switch(result.code){
        case 2: // 连接请求返回
          let j1 = JSON.parse(result.data);
          that.clientData = [];
          j1.forEach(item => {
            that.clientData.push({
              key: item.id,
              label: item.serverName+'-'+item.groupId+'组',
              disabled: item.connectStatus == 1 ? 0 : 1,
            })
          })
          this.$message.success('连接成功！');
          break;
        case 20: // 连接异常
          this.$message.error(result.message);
          break;
        case 4: // 心跳返回
          // 解析抢购机数据
          let json = JSON.parse(result.data);
          that.clientData = [];
          json.forEach(item => {
            that.clientData.push({
               key: item.id,
               label: item.serverName+'-'+item.groupId+'组',
               disabled: item.connectStatus == 1 ? 0 : 1,
            })
          })
          break;
        case 6:
          // 处理抢购流程
          // alert("处理抢购流程");
          debugger;
          let vo = JSON.parse(result.data);
          let code = vo.chipCode;
          let buyNum = vo.buyNum;
          break;
        case 8:// 加载数据请求返回
          let arr = JSON.parse(result.data)
          arr.forEach(item => {
            that.goodsList.push({
              code: item
            })
          })
          this.$message.success('数据加载成功！');
          break;
        default:

      }
      //收到服务器信息，心跳重置
      this.reset();
    },
    websocketsend(msg) {
      //向服务器发送信息
      this.websock.send(msg);
    }
  },
  created() {

  },
  watch: {
  }
}
</script>

<style>
  .tm-dialog-container .tm-dialog-body {
    display: none;
    justify-content: normal;
  }

  .tm-dialog-container .tm-dialog-body {
      padding: 0px;
  }
  .tm-dialog-container .tm-dialog-body {
      padding: 0px;
  }

  .common-layout {
    width: 100%;
  }
  .common-layout .el-footer {
    background-color: #b3c0d1;
    color: var(--el-text-color-primary);
    text-align: center;
    line-height: 60px;
  }
  .common-layout .el-footer {
    line-height: 60px;
  }

  .common-layout .el-aside {
    /* background-color: #d3dce6; */
    color: var(--el-text-color-primary);
    /* text-align: center; */
    /* line-height: 200px; */
  }

  .common-layout .el-main {
    padding-top: 0px;
  }

  .common-layout > .el-container {
    margin-bottom: 40px;
  }

  .common-layout .el-container:nth-child(5) .el-aside,
  .common-layout .el-container:nth-child(6) .el-aside {
    line-height: 260px;
  }

  .common-layout .el-container:nth-child(7) .el-aside {
    line-height: 320px;
  }
</style>